#!/usr/bin/env python
# coding: utf-8

# In[7]:


import cv2
import os


def get_frame_from_video(video_name, frame_time, img_name):
    """
    get a specific frame of a video by time in milliseconds
    :param video_name: video name, include path
    :param frame_time: time of the desired frame
    :param img_dir: path which use to store output image
    :param img_name: name of output image
    :return: None
    """
    vidcap = cv2.VideoCapture(video_name)
    # Current position of the video file in milliseconds.
    vidcap.set(cv2.CAP_PROP_POS_MSEC, frame_time - 1)
    # read(): Grabs, decodes and returns the next video frame
    success, image = vidcap.read()

#     if not os.path.exists(img_dir):
#         os.makedirs(img_dir)

    if success:
        # save frame as JPEG file
        cv2.imwrite(img_name, image)  
    return success


# In[8]:


import requests
import re, json
# 去掉警告
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class LiveVideoDownload(object):
    def __init__(self, up_id, size=10, filename='None.flv'):
        self.up_id = up_id
        self.size_all = size
        self.filename = filename
        self.roomIdRegex = r'"//live\.bilibili\.com/{.*?}"'
        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' + 
                        'Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'}
    
    def getRoomId(self):
        url = 'https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld?mid={}'.format(self.up_id)
        self.Referer = 'https://space.bilibili.com/{}/'.format(self.up_id)
        self.headers['Host'] = 'api.live.bilibili.com'
        self.headers['Referer'] = self.Referer
        response = requests.get(url=url, headers=self.headers).json()
        room_id = response['data']['roomid']
        return room_id

    def getJsonFile(self, room_id):
        url = 'https://api.live.bilibili.com/room/v1/Room/playUrl?cid={}'.format(room_id)
        content = requests.get(url=url, headers=self.headers).text
        return content
       
    def extract(self):
        room_id = self.getRoomId()
        data = self.getJsonFile(room_id)
        data_json = json.loads(data)
        download_url = data_json['data']['durl'][0]['url']
        host = download_url[8:].split('/')[0]
        return download_url, host
    
    def download(self):
        content = self.extract()
        url, host = content
        print(url)
        headers = self.headers
        headers['host'] = host
        headers['referer'] = self.Referer
        # 下载
        size = 0
        chunk_size = 1024
        response = requests.get(url, stream=True)
#         print(response)
        with open(self.filename, 'wb') as file:
            for data in response.iter_content(chunk_size = chunk_size):
                file.write(data)
                size += len(data)/1024/1024
                file.flush()
                # print('[下载进度]: %.2fMB/%.2fMB' % (size, self.size_all))
                if size > self.size_all:  # 一般response的iter_content不大
                    break
        print('下载完成')
                

# if __name__ == '__main__':
#     up_id = '50333369'  # uid 号
#     size_MB = 3 # 下载量为 [size_MB] MB
#     filename = 'test.mp4' #下载文件名
#     liveVideo = LiveVideoDownload(up_id=up_id, size=size_MB, filename=filename)
#     liveVideo.download()


# In[9]:


from pyzbar.pyzbar import decode
from PIL import Image,ImageEnhance
import os


"""
图片包含二维码检测
"""
def qrcode_recongnize(filename):
    """
    :param filename: 图片path + name
    :return: boolean
    """
    image_type = False
    try:
        # 读取图片
        img = Image.open(filename).convert('RGB')
        # 增加亮度
        img = ImageEnhance.Brightness(img).enhance(1.0)
        # 锐利化
        img = ImageEnhance.Sharpness(img).enhance(1.5)
        # 增加对比度
        img = ImageEnhance.Contrast(img).enhance(2.0)
        # 灰度化
        img = img.convert('L')
        # 解码二维码
        result = decode(img)
        if len(result)>0:
            image_type = True
    except:
        pass
    return image_type


# if __name__ == '__main__':
#     filepath="./img/"
#     for parent, dirnames, filenames in os.walk(filepath):
#         for filename in filenames:
#             kk=qrcode_recongnize(filepath,filename)
#             print(filename, kk)


# In[ ]:


if __name__ == '__main__':
    up_id = '280464718'  # uid 号
    size_MB = 2 # 下载量为 [size_MB] MB
    filename = 'test.mp4' #下载文件名
    import time
    count = 0
    while True:
        liveVideo = LiveVideoDownload(up_id=up_id, size=size_MB, filename=filename)
        liveVideo.download()
        time.sleep(0.5)
        jpg_name = r'./img/' + str(count) + '.jpeg'
        success = get_frame_from_video(r'test.mp4', 5, jpg_name)
        time.sleep(0.2)
        if success:
            result = qrcode_recongnize(jpg_name)
            if result:  # 出现二维码提醒自己去扫码并停止监听
                print('检测到视频中出现二维码')
                import winsound
                winsound.MessageBeep()
                winsound.Beep(1000, 5000)  # 主板蜂鸣器, 1000大小持续5秒
                break
        time.sleep(0.5)
        count += 1


# In[ ]:





# In[ ]:




